package com.baitiaojun.video.handler;

import com.baitiaojun.api.domain.video.File;
import com.baitiaojun.api.exception.ConditionException;
import com.baitiaojun.api.util.AESUtil;
import com.baitiaojun.api.util.ConstantUtil;
import com.baitiaojun.api.util.FileUtil;
import com.baitiaojun.video.mapper.FileMapper;
import com.baitiaojun.video.support.FastDFSSupport;
import io.netty.util.internal.StringUtil;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.Map;

/**
 * @类名 FrameGrabberUtil
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2023/1/20 16:41
 * @版本 1.0
 */
@Component
public class FrameGrabHandler {

    @Resource
    private FileMapper fileMapper;

    @Autowired
    private FastDFSSupport fastDFSSupport;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private HttpServletResponse response;

    public String getLocalTempFile(Long id, String md5) throws Exception {
        //根据md5获取File对象
        File file = fileMapper.getFileByMd5(md5);
        //获取group和filepath
        Map<String, String> filePathMap = FileUtil.splitFilePath(file.getUrl());
        String group = filePathMap.get("group");
        String filePath = filePathMap.get("filePath");
        //定义本地文件存放路径
        String localFileUrl = new StringBuilder(ConstantUtil.TEMP_FILE_DOWNLOAD_PATH)
                .append(id).append(".").append(file.getType()).toString();
        //文件下载
        fastDFSSupport.downLoadFile(group, filePath, localFileUrl);
        return localFileUrl;
    }

    public String genericVideoFrame(Long fileId, String md5) throws Exception {
        String localFileUrl = this.getLocalTempFile(fileId, md5);
        FFmpegFrameGrabber fFmpegFrameGrabber = FFmpegFrameGrabber.createDefault(localFileUrl);
        fFmpegFrameGrabber.start();
        //转换器，将帧转换成BufferedImage对象
        Java2DFrameConverter converter = new Java2DFrameConverter();
        String nameExt = "png";
        AESUtil aesUtil = AESUtil.lazyGetAesUtil();
        //获取一个视频帧
        Frame frame = fFmpegFrameGrabber.grabImage();
        fFmpegFrameGrabber.close();
        //帧添转换成bufferedImage，将bufferedImage写入到输出流，再将输出流转换成输入流
        BufferedImage bufferedImage = converter.getBufferedImage(frame);
        ByteArrayOutputStream ous = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, nameExt, ous);
        byte[] bytes = ous.toByteArray();
        InputStream ins = new ByteArrayInputStream(bytes);
        //上传视频帧截取图
        String fullUrl = fastDFSSupport.uploadCommonFile(ins, ConstantUtil.GROUP1, nameExt);
        return aesUtil.encrypt(fullUrl);
    }

    public void getVideoFrame(String filePath) throws Exception {
        if (StringUtil.isNullOrEmpty(filePath)) {
            throw new ConditionException("无效路径");
        }
        filePath = filePath.replace(" ", "+");
        AESUtil aesUtil = AESUtil.lazyGetAesUtil();
        String decryptFilePath = aesUtil.decrypt(filePath);
        Map<String, String> filePathMap = FileUtil.splitFilePath(decryptFilePath);
        String group = filePathMap.get("group");
        String storagePath = filePathMap.get("filePath");
        fastDFSSupport.getThumbnail(group, request, response, storagePath);
    }
}
